<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/7/22  8:59
// +----------------------------------------------------------------------
namespace  Service;
use Common\Model\ApplyView;
use Common\Model\RefundModel;
use Service\WechatService;
use Service\PublicService;

require_once COMMON_PATH . 'WxpayAPI/example/WxPay.JsApiPay.php';
require_once COMMON_PATH . "WxpayAPI/lib/WxPay.Api.php";

require_once COMMON_PATH . "Alipay/AopSdk.php";

//退款服务,提供支付退款
class RefundService {
    function __construct($container) {
        $this->di=$container;
    }
    //微信退款
    public function weixinRefund($pay_id,$user_id){
        $ApplyView=new ApplyView();
        $ApplyView->startTrans();
        $d=$ApplyView->where(['pay_id'=>$pay_id,'user_id'=>$user_id])->find();
        if(!$d){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单不存在,请重试'
            ];
            return $j;
        }
        if($d['order_status']=='0'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单未支付,无法退款'
            ];
            return $j;
        }
        if($d['order_status']=='4'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单已退款'
            ];
            return $j;
        }
        if($d['order_status']=='5'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款已驳回,无法再次处理'
            ];
            return $j;
        }
        if(strtotime(date('Y-m-d',strtotime($d['class_refund_time'])))<time() || strtotime(date('Y-m-d',strtotime($d['class_end'])))<time() ){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'无法退款,退款时间已过'.$d['class_refund_time'].$d['class_name']
            ];
            return $j;
        }
        //生成退款记录
        $Refund=new RefundModel();
        $rj=$Refund->doRefund($d);
        if(!$rj){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款生成错误'
            ];
            return $j;
        }
        PublicService::log('退款模块','创建退款订单,user_id:'.$user_id);

        //付款多少就退多少
        $refund_money=$d['money_real'];
        //微信退款
        $input = new \WxPayRefund();
        $input->SetOut_trade_no(\WxPayConfig::MCHID  . $pay_id);
        $input->SetTotal_fee($refund_money*100);
        $input->SetRefund_fee($refund_money*100);
        $input->SetOut_refund_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        $wxr=\WxPayApi::refund($input);
        if($wxr['result_code']!='SUCCESS'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'微信退款失败'
            ];
            PublicService::log('退款模块','退款失败,'.$wxr.',user_id:'.$user_id);
            return $j;
        }

        PublicService::log('退款模块','退款成功,退款金额:'.$wxr['cash_refund_fee'].'分,user_id:'.$user_id);

        //退款成功后更新退款记录
        $rr=$Refund->completeRefund($pay_id,$rj['refund_id'],$wxr['refund_fee']/100);
        if($rr){
            $ApplyView->commit();
            $j=[
                'status'=>'success',
                'data'=>'退款成功'
            ];
            //退款通知-公众号通知
            $user=M('User')->where(['user_id'=>$user_id])->find();
            WechatService::weixin_notice($user,'您所报名的课程:'.$d['class_name'].',已成功退款,退款金额:￥'.$refund_money);
        }else{
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款失败'
            ];
        }
        return $j;
    }
    public function alipayRefund($pay_id,$user_id){
        require_once(COMMON_PATH."Alipay/alipay.config.php");
        $ApplyView=new ApplyView();
        $ApplyView->startTrans();
        $d=$ApplyView->where(['pay_id'=>$pay_id,'user_id'=>$user_id])->find();
        if(!$d){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单不存在,请重试'
            ];
            return $j;
        }
        if($d['order_status']=='0'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单未支付,无法退款'
            ];
            return $j;
        }
        if($d['order_status']=='4'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'订单已退款'
            ];
            return $j;
        }
        if($d['order_status']=='5'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款已驳回,无法再次处理'
            ];
            return $j;
        }
        if(strtotime(date('Y-m-d',strtotime($d['class_refund_time'])))<time() || strtotime(date('Y-m-d',strtotime($d['class_end'])))<time() ){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'无法退款,退款时间已过'.$d['class_refund_time'].$d['class_name']
            ];
            return $j;
        }
        //生成退款记录
        $Refund=new RefundModel();
        $rj=$Refund->doRefund($d);
        if(!$rj){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款生成错误'
            ];
            return $j;
        }
        PublicService::log('退款模块','创建退款订单,user_id:'.$user_id);

        //付款多少就退多少
        $refund_money=$d['money_real'];
        //支付宝退款
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2016080101692750';
        $aop->rsaPrivateKeyFilePath = '/mnt/www/html/apply/App/Common/Alipay/key/rsa_private_key.pem';
        $aop->alipayPublicKey='/mnt/www/html/apply/App/Common/Alipay/key/alipay_public_key.pem';
        $aop->apiVersion = '1.0';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest ();
        $BizContent='{
            "out_trade_no":"'.$d['pay_id'].'",
            "trade_no":"'.$d['transaction_id'].'",
            "refund_amount":"'.$d['money_real'].'",
            "refund_reason":"正常退款"
        }';
        $request->setBizContent($BizContent);
        $result = $aop->execute ( $request);
        if($result->alipay_trade_refund_response->code!='10000'){
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'支付宝退款失败'
            ];
            PublicService::log('退款模块','退款失败,'.$result.',user_id:'.$user_id);
            return $j;
        }

        PublicService::log('退款模块','退款成功,退款金额:'.$wxr['cash_refund_fee'].'分,user_id:'.$user_id);

        //退款成功后更新退款记录
        $rr=$Refund->completeRefund($pay_id,$rj['refund_id'],$wxr['refund_fee']/100);
        if($rr){
            $ApplyView->commit();
            $j=[
                'status'=>'success',
                'data'=>'退款成功'
            ];
            //退款通知-公众号通知
            $user=M('User')->where(['user_id'=>$user_id])->find();
            WechatService::weixin_notice($user,'您所报名的课程:'.$d['class_name'].',已成功退款,退款金额:￥'.$refund_money);
        }else{
            $ApplyView->rollback();
            $j=[
                'status'=>'error',
                'data'=>'退款失败'
            ];
        }
        return $j;
    }

}